<script setup lang="ts">
import type { GroupVO } from '#/api/register/group/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { groupMerge } from '#/api/register/group';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { mergeSchema } from './data';

const emit = defineEmits<{ reload: [] }>();
const checkedCount = ref(0);
const confirmText = computed(() => {
  return checkedCount.value > 0
    ? `确认合并${checkedCount.value}个参观团`
    : `确认合并`;
});
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: mergeSchema(),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      checkedCount.value = 0;
      return null;
    }
    modalApi.modalLoading(true);

    const { records } = modalApi.getData() as { records: GroupVO[] };

    if (records?.length > 0) {
      checkedCount.value = records.length;
      formApi.updateSchema([
        {
          fieldName: 'id',
          componentProps: {
            options: records.map((item: GroupVO) => {
              return { label: item.name, value: item.id };
            }),
          },
        },
      ]);
      await formApi.setValues({ ids: records.map((item) => item.id) });
    }

    markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues()) as any;
    await groupMerge(data);
    // console.log(data);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal title="参观团合并" class="w-[650px]" :confirm-text="confirmText">
    <BasicForm />
  </BasicModal>
</template>
